package org.example.day10;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.1: 使用ReentrantLock实现同步
 *      ①private Lock lock = new ReentrantLock(); 创建锁对象
 *      ② lock.lock(); 加锁
 *      ③ lock.unlock(); 解锁
 */
public class MyThread5 extends Thread{
    private MyService service;

    public MyThread5(MyService service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.testMethod();
    }

    public static void main(String[] args) {
        MyService service = new MyService();
        MyThread5 a1 = new MyThread5(service);
        MyThread5 a2 = new MyThread5(service);
        MyThread5 a3 = new MyThread5(service);
        MyThread5 a4 = new MyThread5(service);
        MyThread5 a5 = new MyThread5(service);
        a1.start();
        a2.start();
        a3.start();
        a4.start();
        a5.start();
    }
}

class MyService{
    private Lock lock = new ReentrantLock();
    public void testMethod(){
        lock.lock();
        for (int i = 0; i < 5; i++) {
            System.out.println("ThreadName = " + Thread.currentThread().getName() + " -- " + (i+1));
        }
        lock.unlock();
    }
}